# -*- coding: utf-8 -*-
import requests
from lxml import etree
from datetime import timedelta
import re
import time
from loguru import logger
import random
import datetime
import execjs
import traceback
import pymysql
import threading
import sys
import os
import json
from queue import Queue, Empty
from fake_useragent import UserAgent
import concurrent.futures
from src.service.requests_middler import requests_sys
from src.service.requests_middler import proxy_requests_sys
from src.service.requests_middler import insert_shipping_info
from src.service.requests_middler import read_excel
from src.service.requests_middler import read_transport_json
from src.service.requests_middler import get_proxies
ip_queue = Queue()
current_working_directory = os.getcwd()
ua = UserAgent()
random_user_agent = ua.random

stop_threading_event = threading.Event()

total_requests = 0
loss_requests = 0

def proxies_queue():
    # 获取代理并放入队列
    if ip_queue.empty():
        proxy = get_proxies()
        logger.info(f"获取ip代理成功: {proxy}")
        if proxy:
            ip_queue.put(proxy)
        else:
            logger.error(f"获取ip代理失败")
    else:
        proxy = ip_queue.get()
        return proxy

def extract_missing_part(str1, str2):
    set1 = set(str1.split())
    set2 = set(str2.split())
    missing_parts = set1 - set2
    return ' '.join(missing_parts)

def zh_hans_transport(origin_city, destination_city):
    global total_requests
    global loss_requests
    port_mapping = {}
    # file_path = "maeu_ports.json"
    # file_path = os.path.join(current_working_directory + r'/src/crawler', file_path)
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'maeu_ports.json')
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            Menu_json = json.load(file)
    else:
        logger.error(f"不存在文件: {file_path}")
        sys.exit()
    for info in Menu_json['ports']:
        port_mapping[info['portName'].upper()] = {
            'portCode': info.get('portCode'),
            'unLocationCode': info['unLocationCode']
        }
    origin_info = port_mapping.get(origin_city.upper())
    destination_info = port_mapping.get(destination_city.upper())
    if origin_info and destination_info:
        total_requests += 1
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        todate = (datetime.datetime.now() + timedelta(days=28)).strftime('%Y-%m-%d')
        origin_unLocationCode = origin_info['unLocationCode']
        # 天津处理
        if origin_unLocationCode.upper() == "CNTJN":
            origin_unLocationCode = "CNTSN"
        elif origin_unLocationCode.upper() == "CNNBO":
            origin_unLocationCode = "CNNGB"
        print(origin_unLocationCode)
        des_unLocationCode = destination_info['unLocationCode']
        url = "https://ecomm.one-line.com/api/v1/schedule/point-to-point"
        params = {
            "porCode": origin_unLocationCode,
            "delCode": des_unLocationCode,
            "rcvTermCode": "Y",
            "deTermCode": "Y",
            "tsFlag": "",
            "fromDate": f"{date}",
            "toDate": f"{todate}",
            "polCode": "",
            "podCode": "",
            "searchType": "List"
        }
        retry_count = 0
        while retry_count < 3:
            proxies = proxies_queue()
            # res = requests_sys(url, params=params, GET=True)
            res = proxy_requests_sys(url, params=params, GET=True, proxies=proxies) #proxies=proxies
            if res:
                ip_queue.put(proxies)
                js_data = res.json()
                if js_data.get("scheduleLines"):
                    logger.info(f"当前查询 起点:{origin_city} ----> 终点: {destination_city}")
                    logger.info(f"当前请求总数: {total_requests}, 失败请求总数: {loss_requests}")
                    for info in js_data['scheduleLines']:
                        '''if 'EXPRESS' in info['sailInfo'][0]['vsslName']:
                            continue'''
                        item = {}
                        item['origin_code'] = f"{origin_city}({origin_info['unLocationCode']})"
                        podLocationName = destination_city.upper()
                        #处理中转站
                        if port_mapping.get(podLocationName.upper()):
                            if len(info['journeys']) >= 2:
                                item[
                                    'destination_code'] = (f"{podLocationName},{check_country_code(des_unLocationCode)}"
                                                           f"({port_mapping.get(podLocationName.upper()).get('unLocationCode')})")  # check
                                item['depart_date'] = datetime.datetime.strptime(info['sailInfo'][0]['departureDate'],
                                                                                 "%Y-%m-%d %H:%M").date().strftime(
                                    "%Y-%m-%d")
                                item['arrive_date'] = datetime.datetime.strptime(info['journeys'][-1]['berthingDate'],
                                                                                 "%Y-%m-%d %H:%M").date().strftime(
                                    "%Y-%m-%d")
                                item['transport_contractor'] = "ONE"
                                departure_date = datetime.datetime.strptime(item['depart_date'], '%Y-%m-%d')
                                arrival_date = datetime.datetime.strptime(item['arrive_date'], '%Y-%m-%d')
                                days_difference = (arrival_date - departure_date).days
                                item['haulage_time'] = days_difference
                                item['ship_name'] = info['sailInfo'][0]['vsslName']
                                vvdName = info['sailInfo'][0]['vvdName']
                                missing = extract_missing_part(vvdName, item['ship_name'])
                                item['voyage_number'] = missing
                                item['transfer_code'] = None
                                transfer_code = ''
                                code = ''
                                for transfer in list(reversed(info['journeys']))[1:]:
                                    if transfer['transferMode'] == '':
                                        code = transfer["podCode"]
                                        transfer_code = f'{transfer["podName"].split(",")[0]}({transfer["podCode"]})'
                                        break
                                if transfer_code != '' and check_code(code):
                                    item['transfer_code'] = transfer_code
                                item['shipping_lanes'] = info['sailInfo'][0]['serviceLaneCode'] # 航线编号
                                # print(item)
                                insert_shipping_info(item)
                                print('-----中转站处理-----')
                            else:
                                item[
                                    'destination_code'] = (f"{podLocationName},{check_country_code(des_unLocationCode)}"
                                                           f"({port_mapping.get(podLocationName.upper()).get('unLocationCode')})")  # check
                                item['depart_date'] = datetime.datetime.strptime(info['sailInfo'][0]['departureDate'],
                                                                                 "%Y-%m-%d %H:%M").date().strftime(
                                    "%Y-%m-%d")
                                item['arrive_date'] = datetime.datetime.strptime(info['sailInfo'][0]['arrivalDate'],
                                                                                 "%Y-%m-%d %H:%M").date().strftime(
                                    "%Y-%m-%d")
                                item['transport_contractor'] = "ONE"
                                departure_date = datetime.datetime.strptime(item['depart_date'], '%Y-%m-%d')
                                arrival_date = datetime.datetime.strptime(item['arrive_date'], '%Y-%m-%d')
                                days_difference = (arrival_date - departure_date).days
                                item['haulage_time'] = days_difference
                                item['ship_name'] = info['sailInfo'][0]['vsslName']
                                vvdName = info['sailInfo'][0]['vvdName']
                                missing = extract_missing_part(vvdName, item['ship_name'])
                                item['voyage_number'] = missing
                                item['transfer_code'] = None
                                item['shipping_lanes'] = info['sailInfo'][0]['serviceLaneCode']  # 航线编号
                                # print(item)
                                insert_shipping_info(item)
                                print('-----------')
                else:
                    logger.info(f"起点:{origin_city} ----> 终点: {destination_city} 未查询到数据")
                    read_transport_json(transport='ONE', origin_city=origin_city, des_city=destination_city,
                                   fail_result="未查询到数据")
                    loss_requests += 1
                break
            elif res is None:
                logger.info(f"起点:{origin_city} ----> 终点: {destination_city} 未查询到数据")
                read_transport_json(transport='ONE', origin_city=origin_city, des_city=destination_city,
                               fail_result=None)
                break
            elif res == 0:
                retry_count += 1
                logger.info(f"起点:{origin_city} ----> 终点: {destination_city} 未查询到数据, 请求超时")
                read_transport_json(transport='ONE', origin_city=origin_city, des_city=destination_city,
                               fail_result="请求超时")
                loss_requests += 1


def check_code(code):
    # file_path = 'maeu_ports.json'
    # file_path = os.path.join(current_working_directory + r'/src/crawler', file_path)
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'maeu_ports.json')
    with open(file_path, 'r') as f:
        result = f.read()
        f.close()
    null = ''
    true = ''
    false = ''
    result = eval(result)['ports']
    for res in result:
        if code == res['unLocationCode'] and code[0:2] == 'US':
            return True
    return False

def check_country_code(code):
    # file_path = 'maeu_ports.json'
    # file_path = os.path.join(current_working_directory, file_path)
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'maeu_ports.json')
    with open(file_path, 'r') as f:
        result = f.read()
        f.close()
    null = ''
    true = ''
    false = ''
    result = eval(result)['ports']
    for res in result:
        if code == res['unLocationCode'] and code[0:2] == 'US':
            try:
                code = res['regionCode']
                return code
            except:
                return ''
    return ''

def process_route(origin_city, destination_list):
    for destination_city in destination_list:
        zh_hans_transport(origin_city, destination_city)

def zh_hans_spider_run():
    global total_requests
    global loss_requests
    # origin_city_list = [
    #     "Shanghai", "XIAMEN", "NANSHA", "QINGDAO", "YANTIAN", "NINGBO", "Tianjin"
    # ]
    #
    # destination_list = [
    #     "Los Angeles", "Long Beach", "Atlanta", "Baltimore", "Boston", "Buffalo", "Calgary", "Charleston",
    #     "Chicago", "Chippewa Falls", "Cincinnati", "Cleveland", "Dallas", "Denver",
    #     "Detroit", "Edmonton", "EL Paso", "Halifax", "Houston", "Jacksonville",
    #     "Kansas City", "Louisville", "Memphis", "Miami", "Minneapolis", "Montreal",
    #     "Nashville", "New Orleans", "New York", "Norfolk", "Oakland", "Omaha",
    #     "Philadelphia", "Pittsburgh", "Portland", "Prince Rupert", "Saint Louis",
    #     "Salt Lake City", "San Antonio", "Saskatoon", "Savannah", "Seattle",
    #     "Tacoma", "Tampa", "Toronto", "Vancouver", "Winnipeg", "Honolulu", "KAHULUI", "Hilo",
    #     "Kawaihae", "Nawiliwili"
    # ]


    json_path_one = "origin_and_destination.json"
    json_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), json_path_one)
    with open(f'{json_path}', 'r', encoding='utf-8') as f:
        tmp = json.loads(f.read())

    origin_city_list = tmp['origin_city_list']
    destination_list = tmp['destination_list']
    del tmp, json_path, json_path_one

    # with concurrent.futures.ThreadPoolExecutor() as executor:
    #     futures = [executor.submit(process_route, origin_city, destination_list) for origin_city in origin_city_list]

    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        for origin_city in origin_city_list:
            future = executor.submit(process_route, origin_city, destination_list)
            futures.append(future)
            time.sleep(1)

        for future in concurrent.futures.as_completed(futures):
            try:
                future.result()
            except Exception as e:
                # 输出异常详细信息，包括出错的行号
                print(f"An error occurred: {e}")
                print(traceback.format_exc())

    read_excel(transport="ONE", total_requests=total_requests, loss_requests=loss_requests)

if __name__ == '__main__':
    zh_hans_spider_run()
